package com.lb.shopguide.ui.fragment.guide.recommend;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterRecommendGoods;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.base.BaseFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.recommend.RecBannerBean;
import com.lb.shopguide.entity.recommend.RecommendDetailGoodsBean;
import com.lb.shopguide.entity.recommend.RecommendGoodsBean;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.activity.ActivityActivityDetail;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.dialog.DialogShare2Wechat;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.AdJumpUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Create by kangzhao on 2018/11/25
 */
public class FragmentRecommendGoods extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private AdapterRecommendGoods mAdapterRecommendGoods;
    private List<RecommendGoodsBean> mRecommendGoodsBeanList;

    private String zoneCode;
    private String shareUrl;

    public static FragmentRecommendGoods newInstance() {
        return new FragmentRecommendGoods();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_recommend_goods;
    }

    @Override
    public void initData() {
        mRecommendGoodsBeanList = new ArrayList<>();
        initRequest();
    }

    @Override
    public void initView() {
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setTitleText("全部必推商品");
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });

        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无必推商品");
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        noDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapterRecommendGoods = new AdapterRecommendGoods(R.layout.item_recommend_goods_in_list, mRecommendGoodsBeanList);
        mRecyclerView.setAdapter(mAdapterRecommendGoods);

        initListener();
    }

    private void initListener() {
        mAdapterRecommendGoods.setOnRecommendGoodsListener(new AdapterRecommendGoods.OnRecommendGoodsListener() {
            @Override
            public void onShareClick(RecommendGoodsBean bean) {
                int orderEntranceCode = -1;
                int productType = -1;
                if (bean.isSecSymbol()) {
                    orderEntranceCode = AppConstant.RECOMMEND_GOODS;
                    productType = AppConstant.PTYPE_RECOMMEND_GOODS;
                } else {
                    orderEntranceCode = AppConstant.COMMON_GOODS;
                    productType = AppConstant.PTYPE_COMMON_GOODS;
                }
                if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
                    shareUrl = "https://singlepage.storeer.com/activity_2018/eightHalf_index?productCode=" + bean.getProductCode() + "&appEntranceType=" +
                            AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0001" + "&orderEntryCode=" + orderEntranceCode + "&productType=" + productType;
                } else {
                    shareUrl = "https://sintest.storeer.com/activity_2018/eightHalf_index?productCode=" + bean.getProductCode() + "&appEntranceType=" +
                            AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0001" + "&orderEntryCode=" + orderEntranceCode + "&productType=" + productType;
                }
                LogUtils.d("===========url====" + shareUrl);
                DialogShare2Wechat dialogShare2Wechat = DialogShare2Wechat.getDialogShare2Wechat(bean);
                dialogShare2Wechat.show(getFragmentManager(), getPageTag());

                dialogShare2Wechat.setOnDialogClickListener(new DialogShare2Wechat.OnDialogClickListener() {
                    @Override
                    public void onBannerClick(RecBannerBean bean) {
                        dialogShare2Wechat.dismissAllowingStateLoss();
                        jumpLogic(bean);
                    }

                    @Override
                    public void onShareWechat(RecommendGoodsBean recommendGoodsBean) {
                        BizUtil.share(mContext, recommendGoodsBean.getProductName(), recommendGoodsBean.getProductDesc(), shareUrl,
                                recommendGoodsBean.getProductPicUrl(), AppConstant.SHARE_WECHAT);
                    }

                    @Override
                    public void onShareCircle(RecommendGoodsBean recommendGoodsBean) {
                        BizUtil.share(mContext, recommendGoodsBean.getProductName(), recommendGoodsBean.getProductDesc(), shareUrl,
                                recommendGoodsBean.getProductPicUrl(), AppConstant.SHARE_WECHAT_CIRCLE);
                    }

                    @Override
                    public void onShareWechat(RecommendDetailGoodsBean recommendGoodsBean) {

                    }

                    @Override
                    public void onShareCircle(RecommendDetailGoodsBean recommendGoodsBean) {

                    }
                });

            }

            @Override
            public void onCountDownOver(RecommendGoodsBean bean) {
                refresh();//暂时不做单个刷新
            }
        });

        mAdapterRecommendGoods.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position < mRecommendGoodsBeanList.size()) {
                    start(FragmentRecGoodsDetail.newInstance(mRecommendGoodsBeanList.get(position).getProductCode()));
                }
            }
        });
    }

    @Override
    public void finishRefresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(false);
            mAdapterRecommendGoods.loadMoreComplete();
        }
    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentRecommendGoods.class.getCanonicalName();
    }

    @Override
    public void onRefresh() {
        mAdapterRecommendGoods.setEnableLoadMore(false);
        if (mError) {
            mAdapterRecommendGoods.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterRecommendGoods.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    public void refresh() {
        mRecommendGoodsBeanList = new ArrayList<>();
        initRequest();
    }

    private void bindEmpty() {
        mRecommendGoodsBeanList.clear();
        mAdapterRecommendGoods.setNewData(mRecommendGoodsBeanList);

        mNoData = true;
        onRefresh();
    }

    private void bindBanner(RecBannerBean bean) {
        if (mAdapterRecommendGoods.getHeaderLayoutCount() == 0) {
            addHeaderView(bean);
        }
    }

    private void addHeaderView(RecBannerBean bean) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_banner_top, null);
        ImageView ivBanner = view.findViewById(R.id.iv_banner);
        int width = ScreenUtils.getScreenWidth();
        float aspect = 0.432f;
        int height = (int) (width * aspect);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivBanner.getLayoutParams();
        params.width = width;
        params.height = height;
        ivBanner.setLayoutParams(params);
        ImageLoaderUtils.display(mContext, ivBanner, bean.getBannerPicUrl());
        mAdapterRecommendGoods.addHeaderView(view);
        ivBanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bean.setJumpUrl(BizUtil.fixActivityUrl(bean.getJumpUrl(), "XD0013"));
                jumpLogic(bean);
            }
        });
    }

    private void initRequest() {
        getRecommendGoods();
        getAdBanner();
    }


    private void jumpLogic(RecBannerBean bean) {
        BaseFragment fragment = AdJumpUtil.jumpToDestination(bean.getJumpMode(), bean.getPageSdCode(), bean.getRelCode(), bean.getRelName(), bean.getJumpUrl());
        if (fragment instanceof FragmentRecommendHome) {
            pop();
        } else if (fragment instanceof FragmentVirtualActivity) {
            Intent intent = new Intent(getContext(), ActivityActivityDetail.class);
            Bundle bundle = new Bundle();
            bundle.putString(AppConstant.WEB_URL, fragment.getArguments().getString(AppConstant.WEB_URL));
            bundle.putString(AppConstant.WEB_TITLE, fragment.getArguments().getString(AppConstant.WEB_TITLE));
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            start(fragment);
        }
    }

    private void bindData() {
        mAdapterRecommendGoods.setNewData(mRecommendGoodsBeanList);
        if (mAdapterRecommendGoods.getFooterLayoutCount() == 0) {
            View footer = LayoutInflater.from(mContext).inflate(R.layout.layout_rec_common_footer, null);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(56));
            footer.setLayoutParams(params);
            mAdapterRecommendGoods.addFooterView(footer);
        }
    }


    private void getRecommendGoods() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArray = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        RecommendGoodsBean bean = JsonUtil.getGson().fromJson(jsonArray.get(i), RecommendGoodsBean.class);
                        mRecommendGoodsBeanList.add(bean);
                    }
                    bindData();
                } else {
                    bindEmpty();
                }
                finishRefresh();
            }
        };
        ApiMethodGuide.listRecommendProductAll(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private void getAdBanner() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    RecBannerBean bean = (RecBannerBean) JsonUtil.getObject(response.getReturnContent(), RecBannerBean.class);
                    bindBanner(bean);
                }
            }
        };
        ApiMethodGuide.getAdBanner(AppConstant.BANNER_TYPE_ALL_REC, new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }
}
